/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.util;

import com.je.common.base.spring.SpringContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class RedisLockUtils {

    //分布式锁过期时间 s  可以根据业务自己调节
    private static final Long LOCK_REDIS_TIMEOUT = 3L;
    //分布式锁休眠 至 再次尝试获取 的等待时间 ms 可以根据业务自己调节
    public static final Long LOCK_REDIS_WAIT = 500L;

    /**
     * 加锁
     **/
    public static Boolean getLock(String key, String value, long times) throws InterruptedException {
        RedisTemplate redisTemplate = SpringContextHolder.getBean(RedisTemplate.class);
        Boolean lockStatus = false;
        while (!lockStatus) {
            if (times <= 0) {
                break;
            }
            lockStatus = redisTemplate.opsForValue().setIfAbsent(key, value, LOCK_REDIS_TIMEOUT, TimeUnit.SECONDS);
            if (!lockStatus) {
                Thread.sleep(RedisLockUtils.LOCK_REDIS_WAIT);
            }
            times--;
        }
        return lockStatus;
    }

    /**
     * 释放锁
     **/
    public static Boolean releaseLock(String key) {
        RedisTemplate redisTemplate = SpringContextHolder.getBean(RedisTemplate.class);
        return redisTemplate.unlink(key);
    }

}
